/**
 * Created by Administrator on 2017/12/24.
 */
layui.config({
    base: '../build/js/'
}).use(['table','layer','treeselect','form'], function(){
    var layer = layui.layer
        ,$ = layui.jquery
        ,table = layui.table
        ,form = layui.form
        ,treeselect = layui.treeselect
        ,departments=null
        ,layUpdateForm=null
        ,userId=null
        ,allRoles=[]
        ,permissionTreeObj=null;

    var setting = {
        view: {
            selectedMulti: false
        },
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        edit: {
            enable: false
        }
    };

    $(document).ready(function() {
        initDepartmentTree();
        initAllRoles();
        initPermissionTree();
    });

    table.render({
        elem: '#userList'
        ,url:'../user/userList'
        ,where:{locked:-1,keyWord:""}
        ,limit:15
        ,cellMinWidth: 80
        ,cols: [[
            {type:'numbers'}
            ,{type: 'checkbox'}
            ,{field:'id', title:'用户Id', width:100, unresize: true, sort: true}
            ,{field:'username', title:'用户名'}
            ,{field:'realname', title:'真实姓名'}
            ,{field:'phone', title: '电话', minWidth:120}
            ,{field:'email', title: '邮箱', minWidth:120}
            ,{field:'sex', title:'性别', width:85,templet: '#setTpl'}
            ,{field:'locked', title:'是否锁定', align:'center', width:120,minWidth:120,templet: '#lockedTpl', unresize: true}
            ,{title:'操作',fixed: 'right', width:250, align:'center', toolbar: '#userListTableBar'}
        ]]
        ,id: 'userListTable'
        ,page: true
    });

    // //加载角色列表
    // table.render({
    //     elem: '#roles'
    //     ,url:'/role/selectRoles'
    //     ,where:{keyWord:'',deptId:0}
    //     ,method:'post'
    //     ,cellMinWidth: 80
    //     ,cols: [[
    //         {type: 'checkbox'}
    //         ,{field:'title', title:'标题',minWidth:150}
    //         ,{field:'description', title: '描述',minWidth:250}
    //     ]]
    //     ,id: 'roleTable'
    // });

    var $ = layui.$, active = {
        reload: function(){
            var locked=$('input:radio[name="locked"]:checked').val();
            var keyWord=$("#searchKey").val();
            //执行重载
            table.reload('userListTable', {
                page: {
                    page: 1 //重新从第 1 页开始
                }
                ,where: {locked:locked,keyWord:keyWord}
            });
        },
        //批量审核
        batchAudit:function () {
            var checkStatus = table.checkStatus('userListTable')
                ,data = checkStatus.data
                ,userIds="";
            for (var i=0;i<data.length;i++){
                userIds=userIds+data[i].id+",";
            }
            userIds=userIds.substr(0,userIds.length-1);
            var postData={userIds:userIds,locked:1}
            excController("../user/audit",postData);
        },
        //批量禁用用户
        batchForbidden:function () {
            var checkStatus = table.checkStatus('userListTable')
                ,data = checkStatus.data
                ,userIds="";
            for (var i=0;i<data.length;i++){
                userIds=userIds+data[i].id+",";
            }
            userIds=userIds.substr(0,userIds.length-1);
            var postData={userIds:userIds,locked:0}
            excController("../user/audit",postData);
        }
        //分配角色
        ,saveUserRoles:function () {
            var checkStatus = table.checkStatus('roleTable')
                ,data = checkStatus.data
                ,roleIds="";
            var roleIds=[];
            if(data.length>0){
                for (var i=0;i<data.length;i++){
                    roleIds.push(data[i].id);
                }
                var params={userId:userId,roleIds:roleIds}
                // excController("../user/saveUserRole",params);
                $.ajax({
                    type: "post",
                    contentType:"application/json",
                    url: "../user/saveUserRole",
                    data: JSON.stringify(params),
                    success: function(res) {
                        if (res.code == 1) {
                            layer.msg(res.msg, {
                                icon: 1
                            });
                            active['reload'].call(this);
                        } else {
                            layer.msg(res.msg, {
                                icon: 2
                            });
                        }
                    }
                });
            }else{
                layer.msg("请选择角色进行分配", {
                    icon: 2
                });
            }
        }
        ,savePrivatePermission:function () {
            var nodes = permissionTreeObj.getCheckedNodes(true);
            var permissionIds=[];
            var systemId="";
            if(nodes){
                for (var i=0;i<nodes.length;i++){
                    var node=nodes[i];
                    permissionIds.push(node.id);
                    systemId=node.systemId;
                }

                var params={};
                params.userId=userId;
                params.systemId=systemId;
                params.permissionIds=permissionIds;

                $.ajax({
                    type: "POST",
                    url: "../user/savePriPermission",
                    dataType:'json',
                    contentType:'application/json;charset=utf-8',
                    data: JSON.stringify(params),
                    success: function(res){
                        if(res){
                            if(res.code==0){
                                layer.msg(res.msg, {
                                    icon: 1,
                                    time: 3000 //3s后自动关闭
                                });
                            }else{
                                layer.msg(res.msg, {
                                    icon: 2,
                                    time:3000
                                });
                            }
                        }
                    }
                });
            }
        }
    };

    $('.userListToolbar .layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    //监听工具条
    table.on('tool(userList)', function(obj){
        var data = obj.data;
       if(obj.event === 'edit'){
            // layer.alert('编辑行：<br>'+ JSON.stringify(data))
           $("input[name='id']").val(data.id);
           $("input[name='username']").val(data.username);
           $("input[name='realname']").val(data.realname);
           $("input[name='phone']").val(data.phone);
           $("input[name='email']").val(data.email);
           // $("input[name='sex']").attr("value",data.sex);
           $("input[name='deptId']").attr("value",data.deptId);

           $("#locked").attr("checked",data.locked==1?true:false);
           $("input[name='sex'][value="+data.sex+"]").attr("checked",true);

           form.render('checkbox', 'updateUserFilter');
           form.render('radio', 'updateUserFilter');

           treeselect.render({
               elem:'#deptSelectTree',
               check:false,
               data:departments
           });

           layUpdateForm=layer.open({
               title:"修改用户信息",
               type:1,
               area: ['320px', '195px'],
               maxmin:true,
               content:$("#updateUserDiv")
           });
           layer.full(layUpdateForm);
        }else if(obj.event=="assassinRoles"){
            userId=data.id;
           //加载角色列表
           // var userRoles=data.roles;
           $.ajax({
               type: "Get",
               url: "../user/selectUserRoleById/"+userId,
               dataType:'json',
               success: function(res){
                   if(res){
                       if(res.code==0){
                           var userRoles=res.data;
                           if(allRoles){
                               for (var i=0;i<allRoles.length;i++){
                                   allRoles[i].LAY_CHECKED=false;
                                   if(userRoles){
                                       for (var j=0;j<userRoles.length;j++){
                                           if(userRoles[j].id==allRoles[i].id){
                                               allRoles[i].LAY_CHECKED=true;
                                               break;
                                           }
                                       }
                                   }
                               }
                           }
                           table.render({
                               elem: '#roles'
                               ,cellMinWidth: 80
                               ,cols: [[
                                   {type: 'checkbox'}
                                   ,{field:'title', title:'标题',minWidth:150}
                                   ,{field:'description', title: '描述',minWidth:250}
                               ]]
                               ,data:allRoles
                               ,id: 'roleTable'
                           });
                       }else{
                           layer.msg(res.msg, {
                               icon: 2,
                               time:3000
                           });
                       }
                   }
               }
           });

           layUpdateForm=layer.open({
               title:"分配角色",
               type:1,
               area: ['700px', '300px'],
               maxmin:true,
               content:$("#roleTableDiv")
           });
       }else if(obj.event=="assassinPermission"){
           userId=data.id;
           layUpdateForm=layer.open({
               title:"权限分配",
               type:1,
               area: ['25%', '100%'],
               offset: 'r',
               anim: 2,
               scrollbar:true,
               resize:true,
               maxmin:true,
               content:$("#privatePermissionTree")
           });

           $.ajax({
               type: "Get",
               url: "../user/selectPriPermissions/"+userId,
               dataType:'json',
               success: function(res){
                   if(res){
                       if(res.code==0){
                           var permissions=res.data;
                           permissionTreeObj.checkAllNodes(false);
                           if(permissions){
                               for (var i=0;i<permissions.length;i++){
                                   var permission=permissions[i];
                                   var id=permission.id;
                                   var node=permissionTreeObj.getNodeByParam("id",id, null);
                                   if(!(node.children && node.children.length>0)){
                                       permissionTreeObj.checkNode(node, true, true);
                                   }
                               }
                           }
                       }else{
                           layer.msg(res.msg, {
                               icon: 2,
                               time:3000
                           });
                       }
                   }
               }
           });
       }
    });

    //监听锁定操作
    form.on('checkbox(isLocked)', function(obj){
        var userId=this.name;
        var data={userIds:userId,locked:obj.elem.checked?1:0}
        excController("../user/audit",data);
    });

    /**
     * 执行修改用户请求
     * @param url
     * @param data
     */
    function excController(url,data) {
        $.post(url, data, function(res) {
            if(res.code==1){
                layer.msg(res.msg, {
                    icon: 1
                });
                active['reload'].call(this);
            }else{
                layer.msg(res.msg, {
                    icon: 2
                });
            }
        }, 'json');
    }

    function initDepartmentTree() {
        $.post("/department/select", {pId:0,keyWord:""}, function(res) {
            if(res){
                if(res.code==0){
                    departments=res.data;
                    treeselect.render({
                        elem:'#selectDeptTree',
                        check:false,
                        data:departments
                    });
                }else {
                    layer.msg(res.msg, {
                        icon: 2,
                        time:3000
                    });
                }
            }
        }, 'json');
    }

    //修改玩家信息
    form.on('submit(updateUserSubmit)', function(data) {
        var loadIndex = layer.load(2, {
            shade: [0.3, '#333']
        });

        var url="../user/updateUser";
        
        data.field.locked=data.field.locked=="on"?1:0;

        $.post(url,data.field, function(res) {
            loadIndex && layer.close(loadIndex);
            if(res.code==0){
                layer.msg(res.msg, {
                    icon: 1,
                    time:3000
                });
                layer.close(layUpdateForm);
                active['reload'].call(this);
            }else{
                layer.msg(res.msg, {
                    icon: 2,
                    time:3000
                });
            }
        }, 'json');
    });

    /**
     * 查询所有角色信息
     */
    function initAllRoles() {
        $.ajax({
            type: "post",
            url: "/role/selectAllRoles",
            data:{keyWord:'',deptId:0},
            success: function(res) {
                if (res.code == 0) {
                    allRoles=res.data;
                } else {
                    layer.msg(res.msg, {
                        icon: 2
                    });
                }
            }
        });
    }

    /**
     * 查询权限信息,初始化权限树
     */
    function initPermissionTree() {
        $.post("/sysMenu/menuTree", {systemId:"upms"}, function(res) {
            if(res){
                permissionTreeObj =$.fn.zTree.init($("#permissionTree"), setting, res);
                permissionTreeObj.expandAll(true);
            }
        }, 'json');
    }
});
